# encoding:utf-8
# ! /usr/bin/python
# filename: identity.py
'''
该类定义通过POST方式获取OpenStack的块Token
'''

import httplib
import json
from source.confs.constants import Config


class Identity:

    def getToken(self):
        print "get Token.....\n"
        ret = {}
        body = json.dumps(Config.AUTH_DATA)
        headers = {"Content-type": "application/json"}
        httpClient = httplib.HTTPConnection(Config.OpenStack_URL, Config.IdentityService_Port, Config.Request_Timeout)
        try:
            httpClient.request("POST", Config.GetToken_Rest_URL, body=body, headers=headers)
            response = httpClient.getresponse()
            if response.status == 201:
                reponseHeaders = response.getheaders()
                for name, value in reponseHeaders:
                    if name == 'x-subject-token':
                        ret[Config.OPENSTACK_SERVICE_TOKEN] = value;
                        break;
                catalogs = json.loads(response.read())
                for eps in catalogs['token']['catalog']:
                    if eps['name'] == Config.OPENSTACK_SERVICE_NOVA:
                        regions = eps.get('endpoints')
                        for region in regions:
                            if region.get('region_id') == Config.REGION_ID:
                                ret[Config.OPENSTACK_SERVICE_NOVA] = region.get('url')
                    elif eps['name'] == Config.OPENSTACK_SERVICE_CEILOMETER:
                        regions = eps.get('endpoints')
                        for region in regions:
                            if region.get('region_id') == Config.REGION_ID:
                                ret[Config.OPENSTACK_SERVICE_CEILOMETER] = region.get('url')
        except Exception, e:
            print e
        finally :
            if httpClient:
                httpClient.close();
            return ret

